package com.woniuxy.charin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.charin.model.dto.RefundProcessDto;
import com.woniuxy.charin.model.dto.RefundRequestDto;
import com.woniuxy.charin.model.entity.ChargingRecords;
import com.woniuxy.charin.model.request.StopChargingRequest;
import com.woniuxy.charin.model.vo.ChargingRecordsVo;
import com.woniuxy.charin.model.vo.RechargeRecordVo;
import com.woniuxy.charin.service.ChargingRecordsService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@Api(tags = "充电管理")
@Slf4j
@RestController
@RequestMapping("/charging")
public class ChargingRecordsController {

    @Autowired
    private ChargingRecordsService chargingRecordsService;

    /**
     * 添加充电记录
     * @param chargingRecord 充电记录对象
     * @return 添加结果
     */
    @PostMapping("/add")
    public ResponseEntity<String> addChargingRecord(@RequestBody ChargingRecords chargingRecord) {
        boolean result = chargingRecordsService.addChargingRecord(chargingRecord);
        if (result) {
            return ResponseEntity.ok("Charging record added successfully.");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to add charging record.");
        }
    }


    @PostMapping("/stopCharging")
    public ResponseEntity<String> stopCharging(@RequestBody StopChargingRequest request) {
        String orderNumber = request.getOrderNumber();
        String chargingPileNumber = request.getChargingPileNumber();

        // 业务逻辑
        return ResponseEntity.ok("Charging stopped successfully");
    }

    @PostMapping("/chargingRecords")
    public ResponseEntity<Map<String, Object>> getChargingRecords(@RequestBody Map<String, Object> params) {
        log.info("params:{}", params);
        // 提取分页参数，设置默认值
        int pageNum = params.get("pageNum") != null ? Integer.parseInt(params.get("pageNum").toString()) : 1;
        int pageSize = params.get("pageSize") != null ? Integer.parseInt(params.get("pageSize").toString()) : 10;

        // 创建查询参数 Map（不进行非空校验）
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("orderNumber", params.get("orderNumber"));
        queryParams.put("customerName", params.get("customerName"));
        queryParams.put("phoneNumber", params.get("phoneNumber"));
        queryParams.put("status", params.get("status"));
        queryParams.put("stationName", params.get("stationName"));

        // 调用服务层进行查询
        Page<ChargingRecordsVo> chargingRecords = chargingRecordsService.getChargingRecords(queryParams, pageNum, pageSize);

        // 封装返回数据并返回
        Map<String, Object> result = new HashMap<>();
        result.put("data", chargingRecords.getRecords());
        result.put("total", chargingRecords.getTotal());
        result.put("currentPage", chargingRecords.getCurrent());
        result.put("pageSize", chargingRecords.getSize());
        log.info("result:{}", result);

        return ResponseEntity.ok(result);
    }

    /**
     * 提交退款申请
     */
    @PostMapping("/apply")
    public ResponseEntity<Map<String, Object>> submitRefund(@RequestBody Map<String, Object> refundRequest) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 从请求中提取字段
            String orderNumber = (String) refundRequest.get("orderNumber");
            String refundDescription = (String) refundRequest.get("refundReason");
            Double refundAmount = Double.parseDouble(refundRequest.get("refundAmount").toString());

            // 调用服务层处理退款逻辑
            boolean success = chargingRecordsService.submitRefund(orderNumber, refundDescription, refundAmount);

            if (success) {
                response.put("success", true);
                response.put("message", "退款申请提交成功");
            } else {
                response.put("success", false);
                response.put("message", "退款申请提交失败");
            }
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "退款申请处理出错: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/record/{id}")
    public ResponseEntity<ChargingRecordsVo> getChargingRecordById(@PathVariable Long id) {
        try {
            ChargingRecordsVo recordVo = chargingRecordsService.getChargingRecordById(id);
            log.info("recordVo:{}", recordVo);
            return ResponseEntity.ok(recordVo);
        } catch (RuntimeException e) {
            System.out.println("e.getMessage() = " + e.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

    /**
     * 提交退款处理
     */
    @PostMapping("/process")
    public ResponseEntity<Map<String, Object>> processRefund(@RequestBody RefundProcessDto processDto) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean result = chargingRecordsService.processRefund(processDto.getOrderNumber(), processDto.getProcessDescription());
            if (result) {
                response.put("success", true);
                response.put("message", "退款处理成功！");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "退款处理失败！");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
            }
        } catch (RuntimeException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    }



